<template>
  <section class="bill-list">
    <!-- 头部 -->
    <custom-filter
        @search="handleSearch"
        :type="1"
        :haveDefault="true"
        :haveImport="true"
        :haveApprovalSetting="true"
        @importSuccess="getTableData"
        from="billList"
    />
    <!-- 统计模块 -->
    <section class="staticis">
      <a-tabs
          :tab-position="$store.getters.isMobile ? 'top' : 'left'"
          v-model:activeKey="activeSticsKey"
          size="small"
      >
        <a-tab-pane
            v-for="(item, key) in sticsTabData"
            :key="key"
            :tab="item.name"
        >
          <a-row
              type="flex"
              justify="space-around"
              align="middle"
              :style="{ height: $store.getters.isMobile ? undefined : '100px' }"
          >
            <a-col :span="$store.getters.isMobile ? 12 : 4">
              <a-statistic :value="item.receivable.total">
                <template #title>
                  <span>{{ key == "collection" ? "应收" : "应付" }}</span>
                  <span>（{{ item.receivable.count }}笔）</span>
                </template>
              </a-statistic>
            </a-col>
            <a-col :span="$store.getters.isMobile ? 12 : 4">
              <a-statistic title="滞纳金" :value="item.latefee" :precision="2">
              </a-statistic>
            </a-col>
            <a-col :span="$store.getters.isMobile ? 12 : 4">
              <a-statistic :value="item.actualAmount" :precision="2">
                <template #title>
                  <span>{{ key == "collection" ? "实收" : "实付" }}</span>
                </template>
              </a-statistic>
            </a-col>
            <a-col :span="$store.getters.isMobile ? 12 : key === 'collection' ? 3 : 4">
              <a-statistic
                  title="调整"
                  :value="item.adjustAmount"
                  :precision="2"
              >
              </a-statistic>
            </a-col>
            <a-col :span="$store.getters.isMobile ? 12 : key === 'collection' ? 3 : 4">
              <a-statistic
                  :value="item.carryAmount"
                  :precision="2"
              >
                <template #title>
                  <span>结转</span>
                  <a-popover placement="top">
                    <template #content>
                      转入：{{ item.carryInAmount || 0 }}<br/>
                      转出：{{ item.carryOutAmount || 0 }}
                    </template>
                    <ExclamationCircleOutlined style="margin-left: 4px"/>
                  </a-popover>
                </template>
              </a-statistic>
            </a-col>
            <a-col :span="$store.getters.isMobile ? 12 : key === 'collection' ? 3 : 4">
              <a-statistic :value="item.needCollect.total">
                <template #title>
                  <span>{{ key == "collection" ? "需收" : "需付" }}</span>
                  <span>（{{ item.needCollect.count }}笔）</span>
                </template>
              </a-statistic>
            </a-col>
            <a-col v-if="key === 'collection'" :span="$store.getters.isMobile ? 12 : 3">
              <a-statistic
                  :title="`需退（${item.need_refund_total || 0}笔）`"
                  :value="item.need_refund_count"
              >
              </a-statistic>
            </a-col>
          </a-row>
        </a-tab-pane>
      </a-tabs>
    </section>
    <!-- 表格 -->
    <a-table
        sticky
        :dataSource="dataList"
        :columns="columns"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
        rowKey="id"
        :scroll="{ x: 'max-content' }"
        :customRow="customRow"
        class="mt-10"
        :row-selection="rowSelection"
    >
      <template #title>
        <a-row
            type="flex"
            justify="space-between"
            align="middle"
            class="table-header"
        >
          <a-col flex="auto">
            <div style="display: flex; align-items: center">
              <a-tabs v-model:activeKey="billTypeTab" @change="handleTabChange">
                <a-tab-pane
                    v-for="item of tabList"
                    :key="item.value"
                    :tab="item.label + '账单'"
                ></a-tab-pane>
              </a-tabs>
              <a-tag
                  style="margin-left: 30px"
                  closable
                  :visible="tagVisible"
                  @close="tagClose"
              >
                <span style="padding-right: 5px"
                >🌱 提示：Shift+滚轮 可以控制表格横向滚动</span
                >
              </a-tag>
            </div>
          </a-col>

          <a-col style="display: flex; align-items: center">
            <div class="switch-wrap">
              <template v-if="billTypeTab == 1">
                <a-switch
                    v-model:checked="incomeBillsBeforeDate"
                    checked-children="显示"
                    un-checked-children="隐藏"
                    @change="onIncomeSwitchChange"
                />
                <span style="font-size: 12px; padding: 0 8px">{{
                    incomeBillsBeforeDate
                        ? "已显示未到应收期账单"
                        : "已隐藏未到应收期账单"
                  }}</span>
              </template>
              <template v-else>
                <a-switch
                    v-model:checked="outcomeBillsBeforeDate"
                    checked-children="显示"
                    un-checked-children="隐藏"
                    @change="outOutcomeSwitchChange"
                />
                <span style="font-size: 12px; padding: 0 8px">{{
                    outcomeBillsBeforeDate
                        ? "已显示未到应付期账单"
                        : "已隐藏未到应付期账单"
                  }}</span>
              </template>
            </div>
            <a-button class="mr-20" @click="downLoadClick"
            >
              <template #icon>
                <DownloadOutlined/>
              </template>
              导出表格
            </a-button
            >
            <a-dropdown
                :trigger="['click']"
                v-model:visible="colVisible"
                @visibleChange="handleColVisibleChange"
            >
              <InsertRowAboveOutlined
                  style="font-size: 18px; cursor: pointer"
                  title="自定义列显示"
              />
              <template #overlay>
                <a-menu class="drop-menu">
                  <li
                      class="list-group-item"
                      style="border-bottom: 1px solid #f1f1f1"
                  >
                    <a-checkbox
                        v-model:checked="colCheckAll"
                        @change="onCheckAllChange"
                    >
                      <span
                          style="margin-left: 10px; font-size: 12px; padding: 0"
                      >
                        全部
                      </span>
                    </a-checkbox>
                    <a-button type="link" @click="resetColumns">{{
                        $t("恢复默认")
                      }}
                    </a-button>
                  </li>
                  <draggable
                      class="list-group"
                      group="transition-group"
                      v-model="columnsData"
                      v-bind="dragOptions"
                      :move="onMove"
                      filter=".forbid"
                      item-key="id"
                  >
                    <template #item="{ element }">
                      <li
                          :class="
                          element.disabled
                            ? 'list-group-item forbid'
                            : 'list-group-item'
                        "
                      >
                        <span style="display: inline-block">
                          <a-checkbox
                              size="large"
                              v-model:checked="element.checked"
                              :disabled="element.disabled"
                              @change="onCheckItemChange"
                          ></a-checkbox>
                          <span class="title">{{ element.title }}</span>
                        </span>
                        <LockOutlined
                            v-if="element.disabled"
                            style="color: #999999; padding-right: 15px"
                        />
                        <UnorderedListOutlined
                            v-else
                            style="color: #999999; padding-right: 15px"
                        />
                      </li>
                    </template>
                  </draggable>
                </a-menu>
              </template>
            </a-dropdown>
          </a-col>
        </a-row>
        <a-row
            type="flex"
            align="middle"
            justify="space-between"
            class="plr-10 mt-10"
            v-if="selectedRowKeys.length && billTypeTab == 1"
        >
          <a-col flex="auto">
            <a-alert type="info" show-icon>
              <template #message>
                <span>已选择</span>
                <span class="mlr-5 text-blue">{{
                    selectedRowKeys.length
                  }}</span>
                <span>项</span>
                <span class="ml-10">总计需收：</span>
                <span>{{ selectedRowMoney }} 元</span>
              </template>
            </a-alert>
          </a-col>
          <a-col
            class="ml-10"
            v-permission="['billList', 'auth', 'addAdjust']"
            v-if="isAllPay"
          >
            <a-button type="primary" ghost @click="handleRefund()">
              退款
            </a-button>
          </a-col>
          <a-col
              class="ml-10"
          >
            <a-button type="primary" ghost @click="changeCompany()" :loading="changeCompanyLoading">
              修改所属公司
            </a-button>
          </a-col>
          <a-col
              class="ml-10"
              v-permission="['billList', 'auth', 'receiptBuild']"
          >
            <a-button type="primary" ghost @click="goUrl('receipt')">
              开具收据
            </a-button>
          </a-col>
          <a-col class="ml-10" v-permission="['billList', 'auth', 'build']">
            <a-button type="primary" ghost @click="goUrl('invoice')">
              生成开票信息
            </a-button>
          </a-col>
          <a-col
              class="ml-10"
              @click="addPaymentNotice"
              v-permission="['billList', 'auth', 'buildPaymentNotice']"
          >
            <a-button type="primary" ghost> 生成缴费通知单</a-button>
          </a-col>
        </a-row>
      </template>

      <template #headerCell="{ title,column }">
        <template v-if="column.key === 'tax_rule_txt'">
          <a-tooltip>
            <template #title>
              <div>含税单价=不含税单价×（1+适用税率）</div>
              <div>不含税单价=含税单价÷（1+适用税率）</div>
            </template>
            {{ title }}
            <question-circle-outlined/>
          </a-tooltip>
        </template>
      </template>

      <template #bodyCell="{ text, record, index, column }">
        <template v-if="column.key === 'owner_name'">
          {{ record.owner_name }}
          <span v-if="record.bill_status == 2"><a-tag color="red">拆分审批中</a-tag></span>
        </template>
        <template v-if="column.key === 'followup_uid'">
          <span>{{ record.followup_uname || "--" }}</span>
        </template>
        <template v-if="column.key === 'settle_status'">
          <span>{{ record.settle_status_txt || "--" }}</span>
        </template>
        <template v-if="column.key === 'cost_type'">
          <span>{{ record.cost_type_txt || "--" }}</span>
        </template>
        <template v-if="column.key === 'bill_type'">
          <span>{{ record.bill_type_txt || "--" }}</span>
        </template>
        <template v-if="column.key === 'currency'">
          <span>{{ record.currency_txt || "--" }}</span>
        </template>
        <template v-if="column.key === 'timeout_status'">
          <span>{{ record.timeout_status_txt || "--" }}</span>
        </template>
        <template v-if="column.key === 'price'">
          <span>{{ text ? text : "--" }}</span>
        </template>
        <template v-if="column.key === 'lease_square'">
          <span>{{ text ? text + record.lease_square_unit : "--" }}</span>
        </template>
        <template v-if="column.key === 'actual_retreat'">
          <template v-if="billTypeTab == 1">
            <a-tag v-if="record.is_fu == 1" color="red">付</a-tag>
            <a-tag v-else color="green">收</a-tag>
          </template>
          <span>{{ text ? text : "--" }}</span>
        </template>

        <!-- 房间 -->
        <template v-if="column.key === 'room_id'">
          <div v-if="record.build_bind && record.build_bind.room.length > 0">
            <RoomBuildBindInRecord :build_bind="record.build_bind"/>
          </div>
          <span v-else>--</span>
        </template>

        <template v-if="column.key === 'notice_status'">
          <!-- 0:未发送； 2：已发送 -->
          <a-tag color="#ff3141" v-if="text == 0">{{
              record.notice_status_txt
            }}
          </a-tag>
          <a-tag color="#00b578" v-else>{{ record.notice_status_txt }}</a-tag>
        </template>
      </template>
    </a-table>
    <add-notice
        @closeDrawer="addNoticeClose"
        @success="addNoticeSuccess"
        :visible="addNoticeVisible"
        :ids="selectedRowKeys"
    >
    </add-notice>

    <ChangeCompanyModal
        :visible="changeCompanyVisible"
        :billIds="selectedRowKeys"
        @handleClose="changeCompanyVisible = false"
        @handleSuccess="selectCompanySuccess"
    />

    <ExportComponents
        v-if="isExport"
        :visible="isExport"
        :title="titles"
        url="/bill/list"
        service="/org"
        method="post"
        :params="paramses"
        :limit="limites"
        :columnstitle="listHanders"
        :custom_result="array"
        :custom_data="true"
        @customDataFunc="customResult"
        @request="$utils.commonRequest"
        @cancel="changeexport"
    />

    <!--  账单退款  -->
    <BillRefundModal
      :visible="refundVisible"
      :bill-ids="selectedRowKeys"
      @handleClose="refundVisible = false"
      @handleSuccess="handleRefundSuccess"
    />

  </section>
</template>

<script>
import {
  defineComponent,
  ref,
  computed,
  watch,
  createVNode,
  onActivated,
  defineAsyncComponent
} from "vue";
import CustomFilter from "../../../components/contract/CustomFilter/bill.vue";
import {
  InsertRowAboveOutlined,
  ExclamationCircleOutlined,
  QuestionCircleOutlined,
  DownloadOutlined,
  LockOutlined,
  UnorderedListOutlined,
} from "@ant-design/icons-vue";
import request from "../../../common/utils/request";
import store from "../../../store";
import {useRouter} from "vue-router";
import AddNotice from "./AddNotice.vue";
import {Modal, notification, message} from "ant-design-vue";
import dict from "../../../common/utils/dict";
import utils from "../../../common/utils/utils";
import draggable from "vuedraggable";
import moment from "moment";
import {xlsx} from "../../../common/utils/xlsx";
import dayOfYear from "moment/plugin/dayOfYear";
import ChangeCompanyModal from "@/views/bill/AllBills/ChangeCompanyModal.vue";
import RoomBuildBindInRecord from "@/components/RoomBuildBindInRecord/index.vue";
import BillRefundModal from "@/views/bill/AllBills/modules/BillRefundModal.vue";
import {ExportComponents} from "bl-common-vue3";
import dayjs, {Dayjs} from 'dayjs';

moment.extend(dayOfYear);

const COL_RESET_TYPE = "autoBillListColumn";

export default defineComponent({
  name: "billList",
  components: {
    UnorderedListOutlined,
    LockOutlined,
    draggable,
    CustomFilter,
    InsertRowAboveOutlined,
    AddNotice,
    DownloadOutlined,
    ChangeCompanyModal,
    QuestionCircleOutlined,
    ExportComponents,
    ExclamationCircleOutlined,
    RoomBuildBindInRecord,
    BillRefundModal,
  },
  setup() {
    const $router = useRouter();
    const dragOptions = computed(() => {
      return {
        animation: 200,
        group: "description",
        disabled: false,
        ghostClass: "ghost",
      };
    });
    /* 勾选的账单是否都是已结清或者部分结清 */
    const isAllPay = ref(false);
    const refundVisible = ref(false);
    /**
     * @description:  table
     */
    const columns = ref([]);
    const columnsData = ref([]);
    const getColumnsData = (type) => {
      let params = {};
      if (type) {
        params.type = type;
        params.list_type = dict.BILL_LIST_COL_SET;
      } else {
        params.type = dict.BILL_LIST_COL_SET;
      }
      request.get("/org", "/contract/billListColumn", params).then((res) => {
        columnsData.value = res.list;
        getColumns();
      });
    };
    const customCols = [
      "settle_status",
      "cost_type",
      "bill_type",
      "currency",
      "timeout_status",
      "followup_uid",
      "lease_square",
      "notice_status",
    ];
    const priceCols = [
      "bill_amount",
      "receivable_payment",
      "actual_payment",
      "receivable_latefee",
      "invoice_amount",
      "adjust_amount",
      "out_amount",
      "into_amount",
      "tax_rate",
      "tax_amount",
      "tax_rule_txt",
    ];
    const fixedCol = ["owner_name"];
    const sorterCols = [
      "owner_name",
      "start_date",
      "end_date",
      "receivable_payment_date",
      "adjust_amount",
      "out_amount",
      "into_amount",
      "receivable_latefee",
      "bill_amount",
      "actual_payment",
      "actual_retreat",
      "receivable_payment",
    ];
    const titleChangeCol = {
      receivable_payment: {
        1: "应收金额",
        2: "应付金额",
      },
      actual_payment: {
        1: "实收金额",
        2: "实付金额",
      },
      actual_retreat: {
        1: "需收金额",
        2: "需付金额",
      },
      receivable_payment_date: {
        1: "应收日期",
        2: "应付日期",
      },
    };
    const getColumns = () => {
      let arr = [];
      let checkall = true;
      columnsData.value.forEach((item) => {
        if (item.checked) {
          let col = {
            title: item.title,
            dataIndex: item.key,
            key: item.key,
            width: item.width || 150,
          };
          if (titleChangeCol[item.key]) {
            col.title = titleChangeCol[item.key][billTypeTab.value];
          }
          if (priceCols.includes(item.key)) {
            col.customRender = ({text, record, index}) => {
              return text || "--";
            };
          }
          if (fixedCol.includes(item.key)) {
            col.fixed = "left";
          }
          if (sorterCols.includes(item.key)) {
            col.sorter = true;
          }
          arr.push(col);
        } else if (checkall) {
          checkall = false;
        }
      });
      colCheckAll.value = checkall;
      columns.value = [...arr];
    };
    // 下拉显隐
    const colVisible = ref(false);
    const handleColVisibleChange = (visiable) => {
      if (visiable == false) {
        // 调取接口存住选项
        getColumns();
        request
            .post("org", "/user/specialSetting", {
              type: dict.BILL_LIST_COL_SET,
              content: JSON.stringify(columnsData.value),
            })
            .then(() => {
            });
      }
    };
    const resetColumns = () => {
      getColumnsData(COL_RESET_TYPE);
      colVisible.value = false;
    };
    // 监听全部选中
    const colCheckAll = ref(false);
    const onCheckAllChange = (e) => {
      const {checked} = e.target;
      colCheckAll.value = checked;
      columnsData.value.forEach((item) => {
        if (!item.disabled) {
          item.checked = checked;
        }
      });
    };
    // 监听选中
    const onCheckItemChange = (e) => {
      const {checked} = e.target;
      if (checked && columnsDataCheckAll()) {
        colCheckAll.value = true;
      } else {
        colCheckAll.value = false;
      }
    };
    // 是否全选
    const columnsDataCheckAll = () => {
      for (let i in columnsData.value) {
        if (!columnsData.value[i].checked) {
          return false;
        }
      }
      return true;
    };

    const messageMobile = () => {
      message.warn('移动端暂不支持,请前往电脑端管理');
    };

    // 自定义行
    const customRow = (record) => {
      return {
        style: {
          cursor: "pointer",
        },
        onClick: (e) => handleTableRowClick(record),
      };
    };
    // 点击行
    const handleTableRowClick = (record) => {
      const query = {billId: record.id};
      // if (record.contract_id) {
      //   query.contractId = record.contract_id;
      // }
      if (window.__MICRO_APP_ENVIRONMENT__) {
        window.microApp.forceDispatch({
          type: "SetMicroPages",
          microInfo: {
            microId: `org_billDetail_${record.id}`,
            app: 'org',
            name: `账单详情【${record.owner_name}】`,
            url: `/bill/billDetail?billId=${record.id}&noBack=1`,
          }
        })
      } else {
        $router.push({
          name: "billDetail",
          query,
        });
      }

    };

    const page = ref(1);
    const limit = ref(10);
    const total = ref(0);
    const pagination = computed(() => ({
      total: total.value,
      current: page.value,
      pageSize: limit.value,
      showSizeChanger: true,
      pageSizeOptions: ["10", "20", "30", "40", "50", "100"],
    }));
    const loading = ref(false);
    const sort = ref("");
    const order = ref("");
    const handleTableChange = (pager, filters, sorter) => {
      dataList.value = [];
      if (sorter) {
        if (sorter.order) {
          sort.value = sorter.order == "ascend" ? "asc" : "desc";
          order.value = sorter.field;
          if (order.value == "owner_name") {
            order.value = "owner_id";
          }
        } else {
          order.value = "";
          sort.value = "";
        }
      }
      page.value = pager.current;
      limit.value = pager.pageSize;
      getTableData();
    };

    const dataList = ref([]);
    const getTableData = () => {
      if (!isExport.value) {
        loading.value = true;
      }
      return new Promise((resolve) => {
        let params = {
          page: isExport.value ? 1 : page.value,
          limit: isExport.value ? 100000 : limit.value,
          sort: sort.value,
          order: order.value,
          bill_type: billTypeTab.value,
          ...searchValue.value,
        };

        params.is_show =
            billTypeTab.value == 1
                ? incomeBillsBeforeDate.value
                : outcomeBillsBeforeDate.value;
        request
            .post("/org", "/bill/list", {
              ...params,
            })
            .then((res) => {
              if (!isExport.value) {
                dataList.value = res.list;
                total.value = res.total;
                return;
              }
              if (selectedRowKeys.value.length) {
                let list = [];
                selectedRowKeys.value.forEach((rowKey) => {
                  res.list.forEach((item) => {
                    if (rowKey == item.id) {
                      list.push(item);
                    }
                  });
                });
                resolve(list);
                return;
              }
              resolve(res.list);
            })
            .finally(() => {
              loading.value = false;
            });
      });
    };

    const sticsTabData = ref({});
    const activeSticsKey = ref("");
    const getStatisticsData = () => {
      request
          .get("/org", "/bill/statistics", {
            ...searchValue.value,
            is_show:
                billTypeTab.value == 1
                    ? incomeBillsBeforeDate.value
                    : outcomeBillsBeforeDate.value,
          })
          .then((res) => {
            // const {collection, payment} = res.list
            res.list.collection.name = "收款";
            res.list.payment.name = "付款";
            sticsTabData.value = res.list;
            activeSticsKey.value = "collection";
          });
    };

    const searchValue = ref({});
    const handleSearch = (params) => {
      searchValue.value = params;
      getStatisticsData();
      page.value = 1;
      selectedRowKeys.value = [];
      getTableData();
    };

    const tabList = ref([]);
    const billTypeTab = ref(0);
    const handleTabChange = () => {
      getColumns();
      page.value = 1;
      getStatisticsData();
      getTableData();
    };

    // 选择收款账单
    const selectedRowKeys = ref([]);
    const selectedRowMoney = ref(0);
    const rowSelection = computed(() =>
        billTypeTab.value == 1 && dataList.value?.length
            ? {
              selectedRowKeys: selectedRowKeys.value,
              onChange: onSelectedRowChange,
            }
            : null
    );
    const onSelectedRowChange = (keys) => {
      if (keys.length > 100) {
        notification.warning({
          message: "警告",
          description: "您最多可勾选100项",
        });
        return;
      }
      selectedRowKeys.value = keys;
    };
    let selectedRows = [];
    watch(
        () => selectedRowKeys.value,
        (keyList) => {
          let rowArr = [];
          let rowKeys = [];
          selectedRows.forEach((row) => {
            if (keyList.includes(row.id)) {
              rowArr.push(row);
              rowKeys.push(row.id);
            }
          });
          dataList.value.forEach((item) => {
            if (keyList.includes(item.id) && !rowKeys.includes(item.id)) {
              rowArr.push(item);
            }
          });
          selectedRows = rowArr;
          selectedRowMoney.value = 0;
          selectedRows.forEach((item) => {
            selectedRowMoney.value += Number(item.actual_retreat);
          });
          isAllPay.value = selectedRows.every((v) => v.settle_status == 2 || v.settle_status == 3);

          selectedRowMoney.value = selectedRowMoney.value.toFixed(2);
        }
    );

    const goUrl = (type) => {
      if (store.getters.isMobile) {
        messageMobile();
        return;
      }
      const billIds = selectedRowKeys.value.join(",");
      if (type == "receipt") {
        request
            .post("/org", "/receipt/beforeVerify", {
              billIds: selectedRowKeys.value,
            })
            .then(() => {
              window.microApp.forceDispatch({
                type: "SetChildDrawerList",
                info: {
                  props: {
                    title: null,
                    maskCloseable: true,
                    visible: true,
                    closable: false,
                    width: 1200,
                    bodyStyle: {height: '100%',},
                    destroyOnClose: true,
                  },
                  microId: "org_receipt",
                  heightFull: true,
                  app: "org",
                  url: `/bill/receipt?billIds=${billIds}&isClose=true`,
                  params: {
                    isMainDrawer: true,
                    closeSubmitDrawer: () => {
                      getTableData();
                    },
                  }
                },
              })
            })
            .catch((err) => {
              if (err.code == 50024) {
                Modal.confirm({
                  title: () => "提示",
                  content: () =>
                      `当前勾选账单楼宇存在没有配置收据编号生成规则,请先前往配置~`,
                  icon: () => createVNode(ExclamationCircleOutlined),
                  centered: true,
                  okText: () => "前往",
                  onOk() {
                    if (window.__MICRO_APP_ENVIRONMENT__) {
                      window.microApp.forceDispatch({
                        type: "SetMicroPages",
                        microInfo: {
                          microId: `org_ruleList_setting`,
                          app: 'org',
                          name: `收据配置`,
                          url: `/bill/receiptSetting`,
                        }
                      })
                    }
                  },
                });
              } else if (err.code == 50025) {
                Modal.confirm({
                  title: () => "提示",
                  content: () =>
                      err.msg || `当前勾选账单楼宇没有配置收款方信息,请先前往配置~`,
                  icon: () => createVNode(ExclamationCircleOutlined),
                  centered: true,
                  okText: () => "前往",
                  onOk() {
                    if (window.__MICRO_APP_ENVIRONMENT__) {
                      window.microApp.forceDispatch({
                        type: "SetMicroPages",
                        microInfo: {
                          microId: `org_ruleList_setting`,
                          app: 'org',
                          name: `收据配置`,
                          url: `/bill/receiptSetting`,
                        }
                      })
                    }
                  },
                });
              }
            });

        return;
      }
      if (type == "invoice") {
        request
            .post("/org", "/invoice/beforeVerify", {
              billIds: selectedRowKeys.value,
            })
            .then(() => {
              $router.push({
                name: "makeInvoice",
                query: {billIds},
              });
            })
            .catch((err) => {
              if (err.code >= 50020) {
                if (err.code == 50021 || err.code == 50020) {
                  const msg =
                      err.code == 50021
                          ? "费用类型未设置税率信息"
                          : "未配置对应楼宇的发票模板";
                  Modal.confirm({
                    title: () => "提示",
                    content: () => err?.msg || `当前所选的部分账单${msg}，请先前往配置~`,
                    icon: () => createVNode(ExclamationCircleOutlined),
                    centered: true,
                    okText: () => "前往配置",
                    onOk() {
                      if (window.__MICRO_APP_ENVIRONMENT__) {
                        window.microApp.forceDispatch({
                          type: "SetMicroPages",
                          microInfo: {
                            microId: `org_invoice_setting`,
                            app: 'org',
                            name: `发票设置`,
                            url: `/bill/InvoiceSetting?type=template`,
                          }
                        })
                      }
                    },
                  });
                } else if (err.code == 50022) {
                  Modal.confirm({
                    title: () => "提示",
                    content: () =>
                        `所选账单存在未匹配适用模板,是否继续进行开票？`,
                    icon: () => createVNode(QuestionCircleOutlined),
                    centered: true,
                    onOk() {
                      if (window.__MICRO_APP_ENVIRONMENT__) {
                        window.microApp.forceDispatch({
                          type: "SetMicroPages",
                          microInfo: {
                            microId: `org_make_invoice`,
                            app: 'org',
                            name: `生成开票信息`,
                            url: `/bill/makeInvoice?billIds=${billIds}`,
                          }
                        })
                      }
                    },
                  });
                } else {
                  notification.warning({
                    message: "警告",
                    description: err.msg,
                  });
                }
              }
            });
      }
    };

    let initFlag = true;

    const removeUndefined = (obj) => {
      return Object.keys(obj)
          .filter((key) => obj[key] !== undefined)
          .reduce((result, key) => {
            result[key] = obj[key];
            return result;
          }, {});
    };

    // 导出报表
    let timer = null;
    const iframe = document.createElement("iframe");
    const isExport = ref(false);

    let listHanders = ref({})
    let paramses = ref({})
    let array = ref([])
    let limites = ref(500)
    let titles = ref('')


    const downLoadClick = () => {
      array.value = []
      let text = dayjs().format('YYYY-MM-DD-HH:mm:ss')
      titles.value = '账单列表' + text
      console.log(titles.value)
      let handerData = utils.deepClone(columns.value);
      listHanders.value = handerData.reduce((obj, v) => {
        obj[v.key] = v.title;
        if (v.key == "followup_uid") {
          obj[v.key] = undefined;
          v.key = undefined;
          obj["followup_uname"] = "跟进人";
        }
        if (v.key == "bill_type") {
          obj[v.key] = undefined;
          v.key = undefined;
          obj["bill_type_txt"] = v.title;
        }
        if (v.key == "settle_status") {
          obj[v.key] = undefined;
          v.key = undefined;
          obj["settle_status_txt"] = v.title;
        }
        if (v.key == "cost_type") {
          obj[v.key] = undefined;
          v.key = undefined;
          obj["cost_type_txt"] = v.title;
        }
        if (v.key == "currency") {
          obj[v.key] = undefined;
          v.key = undefined;
          obj["currency_txt"] = v.title;
        }
        if (v.key == "currency") {
          obj[v.key] = undefined;
          v.key = undefined;
          obj["currency_txt"] = v.title;
        }
        if (v.key == "timeout_status") {
          obj[v.key] = undefined;
          v.key = undefined;
          obj["timeout_status_txt"] = v.title;
        }
        if (v.key == "notice_status") {
          obj[v.key] = undefined;
          v.key = undefined;
          obj["notice_status_txt"] = v.title;
        }
        return obj;
      }, {});

      paramses.value = {
        sort: sort.value,
        order: order.value,
        bill_type: billTypeTab.value,
        is_show: billTypeTab.value == 1 ? incomeBillsBeforeDate.value : outcomeBillsBeforeDate.value,
        ...searchValue.value,
      };

      isExport.value = true
    };

    const customResult = (ExportList) => {
      ExportList.forEach((item) => {
        item.actual_retreat = Number(item.actual_retreat);
        item.bill_amount = Number(item.bill_amount);
        item.receivable_payment = Number(item.receivable_payment);
        item.actual_payment = Number(item.actual_payment);
        item.room_id =  (item?.build_bind?.room || []).map((room) => {
          return (room?.build_name || room?.extra?.build_name) + '-' + room?.layer_name + "-" + room?.room_name;
        }).join(",");
      });
      array.value = ExportList
    }

    const changeexport = () => {
      isExport.value = false
      message.success('导出成功,请等待文件生成');
    }

    const incomeBillsBeforeDate = ref(false);

    const outcomeBillsBeforeDate = ref(false);

    const onIncomeSwitchChange = (checked) => {
      store.dispatch("SetIncomeBillsBeforeDate", checked).then(() => {
        page.value = 1;
        getStatisticsData();
        getTableData();
      });
    };

    const outOutcomeSwitchChange = (checked) => {
      store.dispatch("SetOutcomeBillsBeforeDate", checked).then(() => {
        page.value = 1;
        getStatisticsData();
        getTableData();
      });
    };

    watch(
        () => store.getters.incomeBillsBeforeDate,
        (val) => {
          incomeBillsBeforeDate.value = val;
        }
    );

    watch(
        () => store.getters.outcomeBillsBeforeDate,
        (val) => {
          outcomeBillsBeforeDate.value = val;
        }
    );

    const init = () => {
      incomeBillsBeforeDate.value = store.getters.incomeBillsBeforeDate;
      outcomeBillsBeforeDate.value = store.getters.outcomeBillsBeforeDate;

      if (initFlag) {
        // 首次进入
        store.dispatch("BillInit").then((res) => {
          console.log("BillInit", res);
          if (res && res.bill_type) {
            tabList.value = res.bill_type;
            billTypeTab.value = res.bill_type[0].value;
            getColumnsData();
            initFlag = false;
          }
        });
      } else {
        getStatisticsData();
        getTableData();
      }
    };

    const tagVisible = ref(false);
    onActivated(() => {
      init();
      selectedRowKeys.value = [];
      if (!Boolean(utils.getStorage("tableShiftTipCache_billList", false))) {
        tagVisible.value = true;
      }
    });
    // 标签关闭
    const tagClose = () => {
      tagVisible.value = false;
      utils.setStorage("tableShiftTipCache_billList", true, false);
    };

    const addNoticeVisible = ref(false);
    const addPaymentNotice = () => {
      if (store.getters.isMobile) {
        messageMobile();
        return;
      }
      let params = selectedRowKeys.value;
      request
          .post("/org", "/notice/beforeVerify", {
            billIds: params,
            needMsg: true,
          })
          .then((res) => {
            if (res.data.pass) {
              selectedRowKeys.value = res.data.matchIds;
              addNoticeVisible.value = true;
            } else {
              Modal.confirm({
                title: "提示",
                content: () => res.msg,
                icon: () => createVNode(ExclamationCircleOutlined),
                centered: true,
                okText: () => "继续",
                onOk() {
                  selectedRowKeys.value = res.data.matchIds;
                  addNoticeVisible.value = true;
                },
              });
            }
          })
          .catch((err) => {
            console.log(err);
            if (err.code == 60023) {
              Modal.info({
                title: "提示",
                content: () => err.msg,
                centered: true,
                okText: () => "确定",
              });
            }
          });
    };

    const addNoticeClose = () => {
      addNoticeVisible.value = false;
    };

    const addNoticeSuccess = () => {
      getTableData();
      addNoticeVisible.value = false;
    };

    const changeCompanyLoading = ref(false);
    const changeCompanyVisible = ref(false);

    const changeCompany = () => {
      if (store.getters.isMobile) {
        messageMobile();
        return;
      }
      changeCompanyLoading.value = true;
      request.post("/org", "/company/modifyBillBranch", {bill_ids: selectedRowKeys.value}).then((res) => {
        changeCompanyLoading.value = false;
        changeCompanyVisible.value = true;
      }).catch(() => {
        changeCompanyLoading.value = false;
      });
    };

    const selectCompanySuccess = () => {
      getTableData();
      changeCompanyVisible.value = false;
    };

    //禁止拖动到id为1的对象
    const onMove = (e) => {
      if (e.relatedContext.element.disabled) return false;
      return true;
    };



    const handleRefund = () => {
      // 选中已结清或者部分结清的账单去退款
      if (store.getters.isMobile) {
        messageMobile();
        return;
      }
      refundVisible.value = true;
    };

    const handleRefundSuccess = () => {
      refundVisible.value = false;
      selectedRowKeys.value = [];
      getTableData();
    };

    return {
      colVisible,
      columns,
      columnsData,
      colCheckAll,
      dataList,
      pagination,
      loading,
      sticsTabData,
      activeSticsKey,
      tabList,
      billTypeTab,
      resetColumns,
      handleColVisibleChange,
      onCheckItemChange,
      onCheckAllChange,
      handleTableChange,
      handleSearch,
      customRow,
      handleTabChange,
      addNoticeVisible,
      addPaymentNotice,
      addNoticeClose,
      addNoticeSuccess,
      rowSelection,
      selectedRowKeys,
      selectedRowMoney,
      goUrl,
      downLoadClick,
      isExport,
      tagClose,
      tagVisible,
      dragOptions,
      onMove,
      getTableData,
      incomeBillsBeforeDate,
      outcomeBillsBeforeDate,
      onIncomeSwitchChange,
      outOutcomeSwitchChange,
      changeCompany,
      changeCompanyLoading,
      changeCompanyVisible,
      selectCompanySuccess,
      paramses,
      listHanders,
      limites,
      titles,
      array,
      changeexport,
      customResult,
      isAllPay,
      refundVisible,
      handleRefund,
      handleRefundSuccess,
    };
  },
});
</script>

<style lang="less" scoped>
.bill-list {
  padding: 10px;

  :deep(.ant-table-title) {
    padding-bottom: 10px;
  }

  .table-header {
    margin: 0 20px;
    color: rgba(0, 0, 0, 0.8);

    &:deep(.ant-tabs-bar) {
      border: none;
      margin: 0;
    }

    // border-bottom: 1px solid #f0f0f0;
  }

  .staticis {
    background: #fff;
    margin-top: 10px;
    width: 100%;
    padding: 10px;

    :deep(.ant-statistic-content) {
      font-size: 20px;
    }
  }
}

.list-group {
  min-height: 20px;
  padding-left: 0;
}

.list-group-item {
  cursor: pointer;
  width: 180px;
  height: 35px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-left: 10px;

  .title {
    margin-left: 10px;
    font-size: 12px;
    width: 120px;
  }
}

.font-12 {
  font-size: 12px;
}

.drop-menu {
  height: 600px;
  overflow-y: scroll;
  /*定义滚动条宽高及背景，宽高分别对应横竖滚动条的尺寸*/

  :deep(.ant-btn-link) {
    margin-right: 0;
  }

  :deep(.ant-checkbox + span) {
    padding: 0;
  }
}

::-webkit-scrollbar {
  width: 5px; /*对垂直流动条有效*/
}

::-webkit-scrollbar-thumb {
  border-radius: 8px;
  background-color: #dddee0;
}

.switch-wrap {
  margin-right: 20px;
  background-color: #f2f2f2;
  border-radius: 20px;
  padding: 5px 10px;
  display: flex;
  align-items: center;
}


</style>
